package com.jt.blog.service;

import com.alibaba.druid.pool.DruidDataSource;
import com.google.common.base.Throwables;
import com.jt.blog.common.model.Response;
import com.jt.blog.common.util.DateKit;
import com.jt.blog.common.util.backup.Backup;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.io.File;
import java.sql.SQLException;

/**
 * @author : 戴瑞
 * @Description :
 * @create : 2018-03-22 21:30
 **/
@Service
public class SetingServiceImpl implements SetingService {

    private Logger log= LoggerFactory.getLogger(SetingServiceImpl.class);

    @Value("${sql-backup}")
    private String backupPath;


    @Autowired
    private DruidDataSource dataSource;

    @Override
    public Response<String> executeBackup() {
        long startTimeMillis = System.currentTimeMillis();
        log.info("开始执行数据库备份...");
        Response<String> response = new Response<>();
        try {
            Backup backup = new Backup(dataSource.getConnection());
            String sqlContent = backup.execute();
            String filePath=backupPath+File.separator+"backup.sql";
            File sqlFile = new File(filePath);
            // 每次覆盖写入，无需删除
            FileUtils.writeStringToFile(sqlFile,sqlContent,"utf-8");
            response.setResult("数据库备份成功");
            log.info("数据库备份成功  耗时{}毫秒",(System.currentTimeMillis()-startTimeMillis));
            log.info("文件地址："+sqlFile.getAbsolutePath());
        } catch (Exception e) {
            log.error("数据库备份失败 原因={}", Throwables.getStackTraceAsString(e));
            response.setError("数据库备份失败,请稍后再试");
        }
        return response;
    }


}
